import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../providers/favorite_provider.dart';
import '../../domain/entities/favorite.dart';
import '../../core/utils/chinese_title_mapper.dart';

/// 收藏页面
class FavoritesPage extends StatefulWidget {
  const FavoritesPage({super.key});

  @override
  State<FavoritesPage> createState() => _FavoritesPageState();
}

class _FavoritesPageState extends State<FavoritesPage> with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  @override
  bool get wantKeepAlive => true;

  late TabController _tabController;
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 5, vsync: this);
    
    // 初始化收藏数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<FavoriteProvider>().initializeFavorites();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: Column(
        children: [
          // 自定义 AppBar
          _buildCustomAppBar(),
          
          // 搜索栏
          if (_isSearching) _buildSearchBar(),
          
          // 状态分类标签
          _buildTabBar(),
          
          // 收藏列表
          Expanded(
            child: _buildTabBarView(),
          ),
        ],
      ),
    );
  }

  Widget _buildCustomAppBar() {
    return Container(
      color: Colors.white,
      child: SafeArea(
        bottom: false,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Row(
          children: [
              const Text(
                '我的收藏',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF2C3E50),
                ),
              ),
              const Spacer(),
              
              // 搜索按钮
              IconButton(
                icon: Icon(
                  _isSearching ? Icons.close : Icons.search,
                  color: const Color(0xFF2C3E50),
                ),
                onPressed: () {
                  setState(() {
                    _isSearching = !_isSearching;
                    if (!_isSearching) {
                      _searchController.clear();
                      _searchQuery = '';
                    }
                  });
                },
              ),
              
              // 排序按钮
              PopupMenuButton<String>(
                icon: const Icon(Icons.sort, color: Color(0xFF2C3E50)),
                onSelected: (value) {
                  // TODO: 实现排序功能
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('按$value排序'),
                      duration: const Duration(seconds: 1),
                    ),
                  );
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(value: '添加时间', child: Text('按添加时间')),
                  const PopupMenuItem(value: '标题', child: Text('按标题')),
                  const PopupMenuItem(value: '评分', child: Text('按评分')),
                  const PopupMenuItem(value: '观看进度', child: Text('按观看进度')),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
      child: TextField(
        controller: _searchController,
        autofocus: true,
        decoration: InputDecoration(
          hintText: '搜索收藏的动漫...',
          prefixIcon: const Icon(Icons.search, color: Colors.grey),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(25),
            borderSide: BorderSide.none,
          ),
          filled: true,
          fillColor: Colors.grey[100],
          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        ),
        onChanged: (value) {
          setState(() {
            _searchQuery = value;
          });
        },
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      color: Colors.white,
      child: Consumer<FavoriteProvider>(
        builder: (context, provider, child) {
          return TabBar(
            controller: _tabController,
            isScrollable: false,
            tabAlignment: TabAlignment.fill,
            indicatorColor: Theme.of(context).primaryColor,
            indicatorWeight: 3,
            labelColor: Theme.of(context).primaryColor,
            unselectedLabelColor: Colors.grey[600],
            labelStyle: const TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w600,
            ),
            unselectedLabelStyle: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.normal,
            ),
            tabs: [
              _buildTab('想看', provider.favoriteStats[FavoriteStatus.wantToWatch] ?? 0),
              _buildTab('在看', provider.favoriteStats[FavoriteStatus.watching] ?? 0),
              _buildTab('已看完', provider.favoriteStats[FavoriteStatus.completed] ?? 0),
              _buildTab('暂停', provider.favoriteStats[FavoriteStatus.onHold] ?? 0),
              _buildTab('弃番', provider.favoriteStats[FavoriteStatus.dropped] ?? 0),
            ],
          );
        },
      ),
    );
  }

  Widget _buildTab(String title, int count) {
    return Tab(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 13,
            ),
          ),
          if (count > 0) ...[
            const SizedBox(height: 2),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                count.toString(),
                style: TextStyle(
                  fontSize: 10,
                  color: Theme.of(context).primaryColor,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildTabBarView() {
    return Consumer<FavoriteProvider>(
      builder: (context, provider, child) {
        if (provider.isLoading) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        if (provider.hasError) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.red[400],
                ),
                const SizedBox(height: 16),
                Text(
                  '加载失败',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  provider.errorMessage,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[500],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    provider.initializeFavorites();
                  },
                  child: const Text('重试'),
            ),
          ],
        ),
          );
        }

        return TabBarView(
          controller: _tabController,
          children: [
            _buildFavoriteList(FavoriteStatus.wantToWatch, provider),
            _buildFavoriteList(FavoriteStatus.watching, provider),
            _buildFavoriteList(FavoriteStatus.completed, provider),
            _buildFavoriteList(FavoriteStatus.onHold, provider),
            _buildFavoriteList(FavoriteStatus.dropped, provider),
          ],
        );
      },
    );
  }

  Widget _buildFavoriteList(FavoriteStatus status, FavoriteProvider provider) {
    List<Favorite> favorites = provider.getFavoritesByStatus(status);
    
    // 如果有搜索查询，过滤结果
    if (_searchQuery.isNotEmpty) {
      favorites = favorites.where((favorite) {
        final query = _searchQuery.toLowerCase();
        return favorite.anime.title.toLowerCase().contains(query) ||
               favorite.anime.titleJapanese.toLowerCase().contains(query) ||
               (favorite.anime.titleEnglish?.toLowerCase().contains(query) ?? false);
      }).toList();
    }

    if (favorites.isEmpty) {
      return _buildEmptyState(status);
    }

    return RefreshIndicator(
      onRefresh: () async {
        await provider.refreshFavoritesByStatus(status);
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: favorites.length,
        itemBuilder: (context, index) {
          return _buildFavoriteCard(favorites[index], provider);
        },
      ),
    );
  }

  Widget _buildEmptyState(FavoriteStatus status) {
    String message;
    IconData icon;
    
    switch (status) {
      case FavoriteStatus.wantToWatch:
        message = '暂无想看的动漫\n快去首页添加喜欢的动漫吧';
        icon = Icons.favorite_border;
        break;
      case FavoriteStatus.watching:
        message = '暂无正在观看的动漫\n开始追番之旅吧';
        icon = Icons.play_circle_outline;
        break;
      case FavoriteStatus.completed:
        message = '暂无已完成的动漫\n完成一部作品后会显示在这里';
        icon = Icons.check_circle_outline;
        break;
      case FavoriteStatus.onHold:
        message = '暂无暂停的动漫\n暂停追番的作品会显示在这里';
        icon = Icons.pause_circle_outline;
        break;
      case FavoriteStatus.dropped:
        message = '暂无弃番的作品\n不感兴趣的动漫会显示在这里';
        icon = Icons.close;
        break;
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            message,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildFavoriteCard(Favorite favorite, FavoriteProvider provider) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: favorite.anime.title,
      titleJapanese: favorite.anime.titleJapanese,
      titleEnglish: favorite.anime.titleEnglish,
      titleSynonyms: favorite.anime.titleSynonyms,
    );

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () {
          Navigator.pushNamed(
            context,
            '/detail',
            arguments: {'id': favorite.anime.id},
          );
        },
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 动漫封面
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: CachedNetworkImage(
                  imageUrl: favorite.anime.imageUrl,
                  width: 60,
                  height: 80,
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Container(
                    width: 60,
                    height: 80,
                    color: Colors.grey[300],
                    child: const Icon(Icons.image, color: Colors.grey),
                  ),
                  errorWidget: (context, url, error) => Container(
                    width: 60,
                    height: 80,
                    color: Colors.grey[300],
                    child: const Icon(Icons.broken_image, color: Colors.grey),
                  ),
                ),
              ),
              
              const SizedBox(width: 12),
              
              // 动漫信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      chineseTitle,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    
                    const SizedBox(height: 4),
                    
                    // 评分和状态
                    Row(
                      children: [
                        if (favorite.anime.score > 0) ...[
                          Icon(Icons.star, size: 14, color: Colors.amber),
                          const SizedBox(width: 2),
                          Text(
                            favorite.anime.score.toStringAsFixed(1),
                            style: const TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(width: 8),
                        ],
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: _getStatusColor(favorite.status).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            favorite.statusText,
                            style: TextStyle(
                              fontSize: 10,
                              color: _getStatusColor(favorite.status),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ],
                    ),
                    
                    const SizedBox(height: 4),
                    
                    // 观看进度
                    if (favorite.watchedEpisodes != null) ...[
          Text(
                        '进度: ${favorite.progressText}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                      
                      // 进度条
                      if (favorite.anime.episodes != null && favorite.anime.episodes! > 0) ...[
                        const SizedBox(height: 4),
                        LinearProgressIndicator(
                          value: favorite.progressPercentage,
                          backgroundColor: Colors.grey[300],
                          valueColor: AlwaysStoppedAnimation<Color>(
                            _getStatusColor(favorite.status),
                          ),
                        ),
                      ],
                    ],
                    
                    // 个人评分
                    if (favorite.personalScore != null) ...[
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          const Text(
                            '我的评分: ',
            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey,
                            ),
                          ),
                          ...List.generate(5, (index) {
                            return Icon(
                              index < (favorite.personalScore! / 2).round()
                                  ? Icons.star
                                  : Icons.star_border,
                              size: 12,
                              color: Colors.amber,
                            );
                          }),
                          const SizedBox(width: 4),
                          Text(
                            favorite.personalScore!.toStringAsFixed(1),
                            style: const TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
              
              // 操作按钮
              PopupMenuButton<String>(
                icon: const Icon(Icons.more_vert, color: Colors.grey),
                onSelected: (value) => _handleMenuAction(value, favorite, provider),
                itemBuilder: (context) => [
                  const PopupMenuItem(value: 'edit_status', child: Text('修改状态')),
                  const PopupMenuItem(value: 'edit_progress', child: Text('更新进度')),
                  const PopupMenuItem(value: 'edit_score', child: Text('评分')),
                  const PopupMenuItem(value: 'edit_notes', child: Text('添加备注')),
                  const PopupMenuDivider(),
                  const PopupMenuItem(
                    value: 'remove',
                    child: Text('移除收藏', style: TextStyle(color: Colors.red)),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _getStatusColor(FavoriteStatus status) {
    switch (status) {
      case FavoriteStatus.wantToWatch:
        return Colors.blue;
      case FavoriteStatus.watching:
        return Colors.green;
      case FavoriteStatus.completed:
        return Colors.purple;
      case FavoriteStatus.onHold:
        return Colors.orange;
      case FavoriteStatus.dropped:
        return Colors.red;
    }
  }

  void _handleMenuAction(String action, Favorite favorite, FavoriteProvider provider) {
    switch (action) {
      case 'edit_status':
        _showStatusDialog(favorite, provider);
        break;
      case 'edit_progress':
        _showProgressDialog(favorite, provider);
        break;
      case 'edit_score':
        _showScoreDialog(favorite, provider);
        break;
      case 'edit_notes':
        _showNotesDialog(favorite, provider);
        break;
      case 'remove':
        _showRemoveDialog(favorite, provider);
        break;
    }
  }

  void _showStatusDialog(Favorite favorite, FavoriteProvider provider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改状态'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: FavoriteStatus.values.map((status) {
            return RadioListTile<FavoriteStatus>(
              title: Text(status.displayName),
              value: status,
              groupValue: favorite.status,
              onChanged: (value) async {
                if (value != null) {
                  Navigator.pop(context);
                  final success = await provider.updateFavoriteStatus(favorite.animeId, value);
                  if (success && mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('状态已更新')),
                    );
                  }
                }
              },
            );
          }).toList(),
        ),
      ),
    );
  }

  void _showProgressDialog(Favorite favorite, FavoriteProvider provider) {
    final controller = TextEditingController(
      text: favorite.watchedEpisodes?.toString() ?? '0',
    );
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('更新观看进度'),
        content: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            labelText: '已观看集数',
            hintText: favorite.anime.episodes != null 
                ? '总共 ${favorite.anime.episodes} 集'
                : '输入已观看集数',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final episodes = int.tryParse(controller.text) ?? 0;
              Navigator.pop(context);
              final success = await provider.updateWatchedEpisodes(favorite.animeId, episodes);
              if (success && mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('进度已更新')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showScoreDialog(Favorite favorite, FavoriteProvider provider) {
    double currentScore = favorite.personalScore ?? 5.0;
    
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('个人评分'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('评分: ${currentScore.toStringAsFixed(1)}'),
              const SizedBox(height: 16),
              Slider(
                value: currentScore,
                min: 0.0,
                max: 10.0,
                divisions: 20,
                onChanged: (value) {
                  setState(() {
                    currentScore = value;
                  });
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                Navigator.pop(context);
                final success = await provider.updatePersonalScore(favorite.animeId, currentScore);
                if (success && mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('评分已更新')),
                  );
                }
              },
              child: const Text('确定'),
            ),
          ],
        ),
      ),
    );
  }

  void _showNotesDialog(Favorite favorite, FavoriteProvider provider) {
    final controller = TextEditingController(text: favorite.notes ?? '');
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加备注'),
        content: TextField(
          controller: controller,
          maxLines: 4,
          decoration: const InputDecoration(
            hintText: '写下你对这部动漫的想法...',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              final success = await provider.updateNotes(favorite.animeId, controller.text);
              if (success && mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('备注已更新')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showRemoveDialog(Favorite favorite, FavoriteProvider provider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('移除收藏'),
        content: Text('确定要移除「${favorite.anime.title}」吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              final success = await provider.removeFavorite(favorite.animeId);
              if (success && mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('已移除收藏')),
                );
              }
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('移除'),
          ),
        ],
      ),
    );
  }
} 